serverUrl="http://sepcv18.deu.hp.com/services/json";
//serverUrl="http://kliu23/~allen/drupal/services/json";
if(localStorage.getItem("serverUrl"))
	serverUrl = localStorage.getItem("serverUrl");
offline = false;

var homeController = null;
var user = null;
function showPrice(user) { 
	return !(user.roles[3] || user.roles[4] || user.roles[5] || user.roles[7]);
}

function setStorageObject(key, value) {
	localStorage.setItem(key, JSON.stringify(value));
}

function getStorageObject(key) {
	return localStorage.getItem(key) && JSON.parse(localStorage.getItem(key));
}

function getCartList(){
	var l = getStorageObject("cart" + user.uid);
	return (l==null) ? [] : l;
}

function addToCart(product) {
	var cartList = getCartList();
	cartList.push(product);
	setStorageObject("cart" + user.uid, cartList);
}

function removeFromCart(product) {
	var cartList = getCartList();
	for(var i in cartList){
		if(cartList[i].nid == product.nid){
			cartList.splice(i,1);
			break;
		}
	}
	setStorageObject("cart" + user.uid, cartList)	
}

function emptyCart(){
	setStorageObject("cart" + user.uid, []);
}

function myAlert(scene, message, bt1Click, bt2Click, bt1Label, bt2Label, backToHome) {
	if(!bt1Label) bt1Label = "Ok";
	if(!bt2Label) bt2Label = "Cancel";
	if(backToHome == undefined) backToHome = false;
	var choices = [{ label : bt1Label, value : 1 }];
	if(bt2Click) choices.push({ label : bt2Label, value : 2 });
	if(backToHome) choices.push({ label : "Back To Home", value : "home" });
	scene.controller.showAlertDialog({
  	onChoose : function(value) { 
  		if(value == 1 && bt1Click) 
  			bt1Click();
  		else if(value == 2 && bt2Click) 
  			bt2Click();
  		else if(value == "home") 
  			Mojo.Controller.stageController.popScenesTo(homeController);
  	},
  	title : "Alert",
  	message : message,
  	choices : choices
  }); 
}

function drupalService(method, args, scene, success){
	if(offline) {
		myAlert(scene, "You are currently in offline mode.")
		return;
	}
	Mojo.Controller.stageController.pushScene("wait");
	if(args == null) args = {};
	args.method = method;
	if(method != 'system.connect')
		args.sessid = localStorage.getItem("sessid");
	for (i in args)
		args[i] = JSON.stringify(args[i]);
	
	new Ajax.Request(serverUrl, {
  		method:'post',
  		parameters: args,
  		onSuccess: function(transport){
				if(transport.status == 0) {
					showSetting();
					return;
				}
  			Mojo.Controller.stageController.popScene();
  			//alert(transport.responseText);
  			try{
     			var r = transport.responseText.evalJSON();
     		}catch(err){
     			//re-connect to server
   				connectToServer();
     		}
     		if(r['#error']){
     			myAlert(scene, r['#data']);
     			return;
     		}
     		var data = r['#data'];
     		if(data && data["#error"]) {
     			if(data["#message"]=="User is not logged in." || data["#message"]=="Access denied"){
						myAlert(scene, data["#message"] + "\nPlease re-login.", function(){
							connectToServer();
						});
					}else {
						myAlert(scene, data["#message"]);
					}
					return;
				}
     		success = success.bind(scene);
  			success(data);
  		},
   		onFailure: function(transport){
				showSetting();
			}
	});
}

function showSetting() {
	Mojo.Controller.stageController.popScenesTo();
	Mojo.Controller.stageController.pushScene("appSetting", {showAlert: true});
}

var db;
initDB();
function initDB(){
    var shortName = 'app';
    var version = '1.0';
    var displayName = 'app';
    var maxSize = 65536;

    db = openDatabase(shortName, version, displayName, maxSize);
    db.transaction(createSchema);
}
function createSchema(transaction) {
	transaction.executeSql(
		'CREATE TABLE products ' +
		'   (nid INTEGER NOT NULL, ' +
		'    title TEXT NOT NULL, ' +
		'    body TEXT, ' +
		'    version TEXT, ' +
		'    vendor TEXT, ' +
		'    price FLOAT, ' +
		'    voting FLOAT,' +
		'    type TEXT, ' +
		'    caty INTEGER);'
	);
}

function loadProducts(reload, scene) {
	if(reload == undefined) reload = false;
	if(scene == undefined) scene = this;
	if("1" == localStorage.getItem("isProductsLoaded") && !reload) return;
	drupalService('views.get', {view_name: "uc_products"}, scene, function(data) {
			setStorageObject("nonEmptyMenu", data.getFieldValues("term_data_tid"));
			db.transaction( function(transaction) {
				transaction.executeSql('DELETE FROM products;',null, null, errorHandler);
				data.each(function(p){
					if(p.node_type == "edicationalitem"){
						p.vendor = "HP Educational";
					}else{
						p.vendor = p.node_data_field_vendor_name_field_vendor_name_value;
						if(!p.vendor) p.vendor = "N/A";
					}
					p.title = p.node_title;
					p.body = p.node_revisions_body;
					p.version = p.node_data_field_softwareversion_field_softwareversion_value
					p.price = p.uc_products_sell_price
					p.voting = p.votingapi_cache_node_percent_vote_average_value;
					p.type = p.node_type ; 
					p.caty = p.term_data_tid;
					transaction.executeSql('INSERT INTO products (nid, title, body, version, vendor, ' +
									'price, voting, type, caty) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);',
							[p.nid, p.title, p.body, p.version, p.vendor, p.price, p.voting, p.type, p.caty],
							null,
							errorHandler.bind(scene));
				});
				localStorage.setItem("isProductsLoaded", "1");
			});
			myAlert(scene, "Sync successfully.");
	});
}

function errorHandler(transaction, error) {
	myAlert(this, 'Error: '+error.message+' (Code '+error.code+')');
	return true;
}

function loadMenu(reload, scene){
	if(reload == undefined) reload = false;
	if(scene == undefined) scene = this;
	if(localStorage.getItem("menu") && !reload) return;
	var args = {vid: 1, parent: 0};
	drupalService('taxonomy.getTree', args, scene, function(data) {
		setStorageObject("menu", data);
		var parentMenu = [];
		data.each(function(m){
			m.parents.each(function(p) {
				parentMenu.push(p);
			});
		});
		setStorageObject("parentMenu", parentMenu.uniq());
		myAlert(scene, "Sync successfully.");
	});
}

function connectToServer(){
	if(offline) {
		Mojo.Controller.stageController.pushScene("home",{parent:0});
		return;
	}
	Mojo.Controller.stageController.popScenesTo();
	drupalService('system.connect', {} , null , function(data){
		localStorage.setItem("sessid", data.sessid);
		if(data.user.uid > 0){
			user = data.user;
			Mojo.Controller.stageController.pushScene("home",{parent:0});
		}else{
			Mojo.Controller.stageController.pushScene("login");
		}
	});
}

function clearCache(){
	userLogout();
	db.transaction( function(transaction) {
		transaction.executeSql('drop table if exists products ;',null, null, errorHandler);
		createSchema(transaction);
	});
	localStorage.clear();
}

function userLogout() {
	Mojo.Controller.stageController.popScenesTo();
	user = null;
	drupalService('user.logout', {}, null, function(data) {
		localStorage.removeItem("username");
		localStorage.removeItem("password");
		connectToServer(false);
	});
}


